package tcl.loan.system.shiro.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import tcl.loan.system.common.config.Constants;

import tcl.loan.system.entity.User;
import tcl.loan.system.service.AccountService;
import tcl.loan.system.utls.UserUtils;


import javax.annotation.PostConstruct;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by linjianding on 2016/12/7.
 */
public class CustomRealm extends AuthorizingRealm {



    protected AccountService accountService;
    /**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String username= token.getUsername();
        String password=new String(token.getPassword());
        final User authentication = accountService.authentication(username, UserUtils.digest(password+UserUtils.salt));
        if (authentication == null) {
            throw new AuthenticationException("用户名或密码错误.");
        }
        return new SimpleAuthenticationInfo(username,password,
                ByteSource.Util.bytes(UserUtils.salt), getName());

    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();
        User screenUserModel = accountService.getUserById(userName);
        if (screenUserModel != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
           // info.addRoles(UserUtils.getUserRoleIdList());
            if (info.getRoles().contains(Constants.SUPER_ADMINISTRATOR_ROLE_ID)) {//判断是否是管理员
                info.addStringPermission("tclloan:*");
            } else {
                info.addStringPermission("tclloan:*");
//                info.addStringPermissions(UserUtils.getPermissionList());
            }
            // 更新登录IP和时间
             screenUserModel.setLastLoginTime(new Date());
            accountService.updateUser(screenUserModel);
            return info;
        } else {
            return null;
        }
    }


    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

}
